import mainApi from "../../api/main";
import session from '../../utils/session'

const auth = {
    namespaced: true,
    state: {
        accessToken: session.getAccessToken(),
        refreshToken: session.getRefreshToken(),
        user: {},
        perms: [],
        roles: []
    },
    mutations: {
        setUser(state,user) {
            state.user = user;
        },
        setPerms(state, perms) {
            state.perms = perms;
        },
        setRoles(state, roles) {
            state.roles = roles;
        },
        remove(state) {
            state.user = {};
            state.perms = [];
            state.roles = [];
        }
    },
    actions: {
        getUserInfo({commit, state}) {
            return new Promise((resolve, reject) => {
                mainApi.doUserMe().then(result => {
                    if(!result) {
                        reject("获取用户信息，请重新尝试");
                    }
                    const { roles, perms} = result.bean;
                    if(!Array.isArray(roles) || roles.length <= 0){
                        reject("登陆失败,该用户没有关联角色");
                    }
                    commit('setRoles',roles);
                    commit('setPerms',perms);
                    commit('setUser',result.bean);
                    resolve({roles, perms, user: auth});
                }).catch(error=>{
                    reject("获取用户信息，请重新尝试");
                })
            });
        }
    }
}

export default auth;
